use serde::{Deserialize, Deserializer, Serialize, Serializer};
use snafu::Snafu;
use std::fmt::{Display, Formatter};
use std::str::FromStr;
use uuid::Uuid;

/// 设备标识，具有唯一性
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Default)]
pub struct DeviceId(Uuid);

#[derive(Debug, Snafu, Deserialize)]
pub enum Error {
    #[snafu(display("Invalid uuid: {}", s))]
    InvalidUuid { s: String },
}

type Result<T> = std::result::Result<T, Error>;

impl Serialize for DeviceId {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0.to_string())
    }
}

impl<'de> Deserialize<'de> for DeviceId {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::new(&s).map_err(serde::de::Error::custom)
    }
}

impl DeviceId {
    pub fn new(s: &str) -> Result<DeviceId> {
        Uuid::parse_str(s.as_ref())
            .map(DeviceId)
            .map_err(|_| Error::InvalidUuid { s: s.to_owned() })
    }
}

impl From<Uuid> for DeviceId {
    fn from(value: Uuid) -> Self {
        Self(value)
    }
}

impl From<DeviceId> for Uuid {
    fn from(value: DeviceId) -> Self {
        value.0
    }
}

impl Display for DeviceId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for DeviceId {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Self::new(s)
    }
}
